package com.punai.customer.controller;

import cn.hutool.core.util.StrUtil;
import com.punai.common.annotation.Log;
import com.punai.common.core.controller.BaseController;
import com.punai.common.core.domain.AjaxResult;
import com.punai.common.core.page.TableDataInfo;
import com.punai.common.enums.BusinessType;
import com.punai.common.utils.file.FileUtils;
import com.punai.customer.domain.CusMaterialItem;
import com.punai.customer.domain.CusVersionsDiscrepancy;
import com.punai.customer.domain.contants.CusConstants;
import com.punai.customer.domain.request.CusMaterialItemRequest;
import com.punai.customer.domain.request.CusRewriteCodeRequest;
import com.punai.customer.service.ICusMaterialItemService;
import com.punai.customer.service.ICusVersionsDiscrepancyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 材料费用项Controller
 *
 * @author zxw
 * @date 2022-12-04
 */
@RestController
@RequestMapping("/cus/materialItem")
public class CusMaterialItemController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(CusMaterialItemController.class);

    @Autowired
    private ICusMaterialItemService cusMaterialItemService;
    @Autowired
    private ICusVersionsDiscrepancyService cusVersionsDiscrepancyService;

    /**
     * 查询材料费用项列表
     */
    @PreAuthorize("@ss.hasPermi('cus:materialItem:list')")
    @GetMapping("/list")
    public TableDataInfo list(CusMaterialItem cusMaterialItem)
    {
        if (StrUtil.isEmpty(cusMaterialItem.getChapterId())) {
            getDataTable(new ArrayList<>());
        }
        startPage();
        cusMaterialItem.setCompanyId(getCompanyId());
        List<CusMaterialItem> cusMaterialItems = cusMaterialItemService.selectCusMaterialItemList(cusMaterialItem);
        return getDataTable(cusMaterialItems);
    }

    /**
     * 获取材料费用项详细信息
     */
    @PreAuthorize("@ss.hasPermi('cus:materialItem:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(cusMaterialItemService.selectCusMaterialItemById(id,getCompanyId()));
    }

    /**
     * 新增材料费用项
     */
    @PreAuthorize("@ss.hasPermi('cus:materialItem:add')")
    @Log(title = CusConstants.CL_NAME, businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CusMaterialItemRequest cusMaterialItemRequest)
    {
        return toAjax(cusMaterialItemService.insertCusMaterialItem(cusMaterialItemRequest));
    }

    /**
     * 修改材料费用项
     */
    @PreAuthorize("@ss.hasPermi('cus:materialItem:edit')")
    @Log(title = CusConstants.CL_NAME, businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CusMaterialItemRequest cusMaterialItemRequest)
    {
        return toAjax(cusMaterialItemService.updateCusMaterialItem(cusMaterialItemRequest));
    }

    @PreAuthorize("@ss.hasPermi('cus:materialItem:editChapter')")
    @Log(title = CusConstants.CL_NAME + "-移动费用项", businessType = BusinessType.UPDATE)
    @PutMapping("/moveToChapter/{ids}/{chapterId}")
    public AjaxResult moveToChapter(@PathVariable String[] ids,@PathVariable String chapterId)
    {
        return toAjax(cusMaterialItemService.moveToChapter(ids,chapterId,getCompanyId()));
    }

    /**
     * 删除材料费用项
     */
    @PreAuthorize("@ss.hasPermi('cus:materialItem:remove')")
    @Log(title = CusConstants.CL_NAME, businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<String> ids)
    {
        return toAjax(cusMaterialItemService.deleteCusMaterialItemByIds(ids,getCompanyId()));
    }

    @GetMapping(value = "/countChapterIdIsZero")
    public AjaxResult countChapterIdIsZero()
    {
        return AjaxResult.success(cusMaterialItemService.countChapterIdIsZero(getCompanyId()));
    }

    @PreAuthorize("@ss.hasPermi('cus:materialItem:rewritecode')")
    @Log(title = CusConstants.CL_NAME + "-重新编码", businessType = BusinessType.UPDATE)
    @PostMapping("/rewriteCode")
    public AjaxResult rewriteCode(@RequestBody CusRewriteCodeRequest codeRequest)
    {
        return toAjax(cusMaterialItemService.rewriteCode(codeRequest));
    }

    @Log(title = CusConstants.CL_NAME + "-下载模板", businessType = BusinessType.UPDATE)
    @PostMapping("/downloadMaterialExcelTemplate")
    public void downloadMaterialExcelTemplate(HttpServletResponse response)
    {
        try
        {
            String mechanicalExcelName = CusConstants.MechanicalExcelName;
            Resource resource = new ClassPathResource("template/"+mechanicalExcelName);
            //放弃使用直接获取文件的方式, 改成使用流的方式
            BufferedInputStream bis = new BufferedInputStream(resource.getInputStream());
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, "材料导入模板.xlsx");
            FileUtils.downloadFile(bis, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    @GetMapping( "/validateCode")
    public AjaxResult validateCode()
    {
        return AjaxResult.success(cusMaterialItemService.validateCode(getCompanyId()));
    }

    @GetMapping("/getContrastData")
    public TableDataInfo getDataLog(CusVersionsDiscrepancy cusVersionsDiscrepancy) {
        startPage();
        cusVersionsDiscrepancy.setCompanyId(getCompanyId());
        cusVersionsDiscrepancy.setPublishType(CusConstants.CL_TYPE);
        return getDataTable(cusVersionsDiscrepancyService.selectStaVersionsDiscrepancyList(cusVersionsDiscrepancy));
    }

    /**
     * 获取材料费用项详细信息
     */
    @GetMapping(value = "/getStaMaterialItem/{id}")
    public AjaxResult getStaMaterialItem(@PathVariable("id") String id)
    {
        return AjaxResult.success(cusMaterialItemService.getStaMaterialItemById(id,getCompanyId()));
    }
}
